package cn.unknowpupil.common.security.interceptor;

import cn.hutool.json.JSON;
import cn.unknowpupil.common.core.resopnse.ResultResponse;
import cn.unknowpupil.common.core.utils.MapperUtils;
import cn.unknowpupil.common.core.utils.ServletUtils;
import cn.unknowpupil.common.core.utils.StringUtils;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * Created at 2020/10/19 by w10g <br>
 * Initialize AuthenticationEntryPointImpl ... <br>
 *
 * 认证失败处理类 返回未授权
 * @author unknowpupil
 * @since 0.0.1
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = 2640065615481728092L;

    @SneakyThrows
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        int code = HttpStatus.UNAUTHORIZED.value();
        String path = request.getRequestURI();
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", path);
        ServletUtils.renderString(response, MapperUtils.obj2json(ResultResponse.buildFailure(code, msg,path)));
    }
}